package com.zhangc.blog.base.utils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 功能描述:<br>
 *
 * @author wx:fdzhangc
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class FileUtils {
    // static目录下的upload目录可自己建，也可不建。因为在上传的时候，会判断是否存在，若不存在便自动创建
    //private static final String prePath = System.getProperty("user.dir") + "/src/main/resources/static/upload/";

    // 用户头像默认上传路径
    public static String UPLOAD_AUTHOR_IMG = "/tmp/myblog/authorImg/";
    // 文章图片默认上传路径
    public static String FILE_UPLOAD_DIC = "/tmp/myblog/";
    // 用户头像数据库路径
    public static String SQL_AUTHOR_IMG = "/authorImg/";
    // 文章图片数据库路径
    public static String FILE_SQL_DIC = "/upload/";

    @Value("${upload.uploadAuthorImg}")
    public void setUploadAuthorImg(String uploadAuthorImg) {
        FileUtils.UPLOAD_AUTHOR_IMG = uploadAuthorImg;
    }

    @Value("${upload.article.img.serverpath}")
    public void setFileUploadDic(String fileUploadDic) {
        FileUtils.FILE_UPLOAD_DIC = fileUploadDic;
    }

    @Value("${upload.sqlAuthorImg}")
    public void setSqlAuthorImg(String sqlAuthorImg) {
        FileUtils.SQL_AUTHOR_IMG = sqlAuthorImg;
    }

    @Value("${upload.article.img.sqlpath}")
    public void setFileSqlDic(String fileSqlDic) {
        FileUtils.FILE_SQL_DIC = fileSqlDic;
    }

    /**
     * 获取图片后缀
     *
     * @param file
     * @return
     */
    public static String getSuffixName(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 功能描述: <br>
     * 〈生成文件名称通用方法〉
     *
     * @param suffixName suffixName
     * @return java.lang.String
     * @author zhangc
     */
    public static String getNewFileName(String suffixName) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        int random = new Random().nextInt(100);
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(random).append(suffixName);
        return tempName.toString();
    }

    /**
     * 上传文件
     *
     * @param file
     * @return 返回文件路径（以相对路径放回）
     */
    public String uploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            return "";
        }
        // 获取原文件名
        String originFileName = file.getOriginalFilename();
        // 我们通过UUID 来重新重组文件名
        String uid = UUID.randomUUID().toString();
        assert originFileName != null;
        String suffix = originFileName.substring(originFileName.lastIndexOf('.') + 1);
        String path = FileUtils.FILE_UPLOAD_DIC + uid + "." + suffix;
        String returnPath = FileUtils.FILE_SQL_DIC + uid + "." + suffix;
        File newFile = new File(path);
        if (newFile.getParentFile() != null && !newFile.getParentFile().exists()) {
            System.out.println("创建目录ing");
            // 上面的 newFile.getParentFile() 已经保证了不为null.
            if (newFile.getParentFile().mkdirs()) {
                System.out.println("创建目录成功");
            } else {
                System.out.println("创建目录失败");
                return "";
            }
        }
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return returnPath;
    }
}
